<?php
namespace Business;
class ProductModel{
    static public function getLatestList($category_id = null,$per_page =10){
        $res = new \ProductModel();
        $res = $res->with('info');
        $res = $res->join('product_category as pc','product.product_id', '=', 'pc.product_id');
        if($category_id){
            $category_id = (!is_array($category_id))?array($category_id):$category_id;
            $res = $res->whereIn('category_id',$category_id);
        }
        $res = $res->where('onsale_status',1)
            ->where('stock_status',1)
            ->paginate($per_page);
        if($res){
            $page = $res->toArray();
            $data['data']= $page['data'];
            unset($page['data']);
            $data['page']= $page;
        } else {
            $data = array();
        }
        return $data;
    }
    static public function getFeaturedList($per_page =10){
        $res = new \ProductModel();
        $res = $res->with('info');
        $res = $res->join('product_featured as pf','product.product_id', '=', 'pf.product_id');
        $res = $res->where('onsale_status',1)
            ->where('stock_status',1)
            ->paginate($per_page);
        if($res){
            $page = $res->toArray();
            $data['data']= $page['data'];
            unset($page['data']);
            $data['page']= $page;
        } else {
            $data = array();
        }
        return $data;
    }
    static public function getRecommendList($per_page) {
        $res = new \ProductModel();
        $res = $res->with('info');
        $res = $res->join('product_recommend as pf','product.product_id', '=', 'pf.product_id');
        $res = $res->where('onsale_status',1)
            ->where('stock_status',1)
            ->paginate($per_page);
        if($res){
            $page = $res->toArray();
            $data['data']= $page['data'];
            unset($page['data']);
            $data['page']= $page;
        } else {
            $data = array();
        }
        return $data;

    }
    static public function getDiscountList($min = null,$max=null,$per_page =10){
        //print_r(\ProductModel::paginate()->toArray());
        $res = new \ProductModel();

        $res = $res->with('info');
        $res = $res->join('product_discount as pd','product.product_id', '=', 'pd.product_id');
        //$res = $res->groupBy('pd.product_id');
        if(!is_null($min)) {
            $res = $res->where('pd.price','>=',$min);
        }
        if(!is_null($max)) {
            $res = $res->where('pd.price','<=',$max);
        }
        $res = $res->where(function($query){
            $query = $query->where('pd.start_at','0000-00-00 00:00:00');
            $query = $query->orWhere('pd.start_at','>=',date('Y-m-d H:i:s'));
        });
        $res = $res->where(function($query){
            $query = $query->where('pd.end_at','0000-00-00 00:00:00');
            $query = $query->orWhere('pd.end_at','<=',date('Y-m-d H:i:s'));
        });
        $res = $res->orderBy('pd.priority','desc');
        $res = $res->orderBy('pd.price','asc');
        $res = $res->where('onsale_status',1)
            ->where('stock_status',1)
            ->paginate($per_page);
        if($res){
            $page = $res->toArray();
            $data['data']= $page['data'];
            unset($page['data']);
            $data['page']= $page;
        } else {
            $data = array();
        }
        //print_R($data);
        //\DB::connection()->enableQueryLog();
        //print_R(\DB::getQueryLog());
        //die;
        return $data;
    }
    static public function getProduct($product_id,$category =0){
        $res = new \ProductModel();
        $res = $res->with('info');
        $res = $res->with('field');
        $res = $res->where('product_id',$product_id);
        $res = $res->first();
        if($res){
            $data= $res->toArray();
            $score =\CommentModel::where('product_id',$product_id)->avg('score');
            if ($category == 1) {
                $cate = \ProductCategoryModel::where('product_id',$product_id)
                    ->join('category','category.category_id','=','product_category.category_id')
                    ->get();
                if($cate) {
                    $list = $cate->toArray();
                    $tree = \Tools::list_to_tree($list, $pk = 'category_id', $pid = 'parent_id', $child = 'sub', $root = 0);
                    $data['category_tree'] = $tree;
                }
            }
            $data['count_score'] = $score?:0;
        } else {
            $data = array();
        }
        return $data;
    }
    //获得某个商品的价格
    static public function getProductPrice($pid,$product_discount_id = 0){
        $res = null;
        if ($product_discount_id) {
            $datetime = date('Y-m-d H:i:s');
            $res = new \ProductDiscountModel();
            $res = $res->where('product_discount_id',$product_discount_id);
            $res = $res->where('product_id',$pid);
            $res = $res->where(function($query) use($datetime){
                $query = $query->where('start_at','0000-00-00 00:00:00');
                $query = $query->orWhere('start_at','>=',$datetime);
            });
            $res = $res->where(function($query) use($datetime){
                $query = $query->where('end_at','0000-00-00 00:00:00');
                $query = $query->orWhere('end_at','<=',$datetime);
            });
            $res = $res->pluck('price');
        }
        if (!$res) {
            $res = new \ProductModel();
            $res = $res->where('product_id',$pid);
            $res = $res->pluck('price');
        }
        return $res;
    }
    static public function getComment($product_id,$rank,$per_page=10) {
        $res = new \CommentModel();
        $res = $res->select(array('comment.*','u.nickname','u.realname'));
        $res = $res->join('user as u','u.id','=','comment.user_id');
        $res = $res->where('comment.product_id',$product_id);
        if($rank == 'A'){
            $res = $res->where('score','>=',3);
        }else if($rank == 'B') {
            $res = $res->where('score','=',2);
        }else if($rank == 'C'){
            $res = $res->where('score','<=',1);
        }
        $res = $res->paginate();
        if($res){
            $page= $res->toArray();
            $data['data']= $page['data'];
            unset($page['data']);
            $data['page']= $page;
        } else {
            $data = array();
        }
        return $data;
    }
    static public function getCommentCount($product_id) {
        $score['ALL'] =\CommentModel::where('product_id',$product_id)->count('score');
        $score['A'] =\CommentModel::where('product_id',$product_id)->where('score','>=',3)->count('score');
        $score['B'] =\CommentModel::where('product_id',$product_id)->where('score','=',3)->count('score');
        $score['C'] =\CommentModel::where('product_id',$product_id)->where('score','<=',3)->count('score');
        foreach ($score as $k =>&$v) {
            if (!$v) {
                $v = 0;
            }
        }
        return $score;
    }
    static public function addToComment($user_id,$product_id,$title = '',$content = '',$score = 3) {
        $order = \OrderProductModel::where('user_id',$user_id)->where('product_id',$product_id)->first();
        if (!$order) {
            return false;
        }
        $res = new \CommentModel();
        $res->user_id = $user_id;
        $res->product_id = $product_id;
        $res->title = $title;
        $res->content = $content;
        if( !$res->save() ){
            return null;
        }
        return true;
    }
    static public function countData(){
        //统计数据
        //\DB::connection()->enableQueryLog();
        //$sqls = \DB::getQueryLog();
        //统计销售量
        $s= \OrderModel::select(array('op.product_id',\DB::raw('sum(quantity) as sales_num')))
            ->join('order_product as op','order.order_id','=','op.order_id')
            ->groupBy('op.product_id')
            //->where('order.pay_status',1)
            ->get();
        foreach ($s as $k=>$v) {
            $res = \ProductCountModel::where('product_id',$v['product_id'])->first();
            if (!$res) {
                $res = new \ProductCountModel();
            }
            $res->product_id = $v['product_id'];
            $res->sales_num = $v['sales_num'];
            $res->save();
        }
        unset($s);
        //统计评分总数、评分总人数、星级
        $s= \CommentModel::select(array('product_id',\DB::raw('sum(score) as comment_score'),\DB::raw('count(score) as comment_num')))
            ->groupBy('product_id')
            //->where('order.pay_status',1)
            ->get();
        foreach ($s as $k=>$v) {
            $res = \ProductCountModel::where('product_id',$v['product_id'])->first();
            if (!$res) {
                $res = new \ProductCountModel();
            }
            $res->product_id = $v['product_id'];
            $res->comment_score = $v['comment_score'];
            $res->comment_num = $v['comment_num'];
            $res->comment_star = $v['comment_score']/$v['comment_num'];
            $res->save();
        }
        unset($s);

    }
    static public function getSearch($kw=null,$orderby=null,$per_page=10){
        require_once '/usr/local/xunsearch/sdk/php/lib/XS.php';
        /*
        SELECT pi.*,pf.value_string as author FROM `product_info` as pi join `product_field` as pf on pi.product_id = pf.product_id where pf.name ='author'
        $xs = new \XS('bookshop');
        $search = $xs->search;
        $search->setLimit(5, 0);
        $docs = $search->search();
        foreach ($docs as $doc) {
            $subject = $search->highlight($doc->name); // 高亮处理 subject 字段
            $message = $search->highlight($doc->author); // 高亮处理 message 字段
            echo $doc->rank() . '. ' . $subject . " [" . $doc->percent() . "%] - ";
            echo date("Y-m-d", $doc->chrono) . "\n" . $message . "\n";
        }
        */
        $res = new \ProductInfoModel();
        //$res = $res->with('field');
        $res = $res->select(array(
            'product_info.*',
            'p.price',
            'pc.comment_star',
            'pfa.value_string as author'
        ));
        if ($kw) {
            $res = $res->where('product_info.name','like','%'.$kw.'%');
        }
        $res = $res->join('product_field as pfa','product_info.product_id','=','pfa.product_id');
        $res = $res->where('pfa.name','author');
        $res = $res->join('product as p','product_info.product_id','=','p.product_id');
        $res = $res->leftJoin('product_count as pc','product_info.product_id','=','pc.product_id');
        if ($orderby) {
            //销售 价格 评论数 评分 出版时间 上架时间
            $orderby = explode(',',$orderby);
            if ($orderby[0] == 'sales_num') {
                $orderField = 'pc.sales_num';
            } else if ($orderby[0] == 'price') {
                $orderField = 'p.price';
            } else if ($orderby[0] == 'comment_num') {
                $orderField = 'pc.comment_num';
            } else if ($orderby[0] == 'comment_score') {
                $orderField = 'pc.comment_score';
            }
            if (isset($orderby[1]) && $orderby[1] =='asc') {
                $by = 'asc';
            } else {
                $by = 'desc';
            }
            $res = $res->orderBy($orderField,$by);
        }
        $res = $res->paginate($per_page);
        if ($res) {
            $page = $res->toArray();
            $data['data']= $page['data'];
            unset($page['data']);
            $data['page']= $page;

        }else{
            $data = Array();
        }
        return $data;
    }
}
